<template>
  <div>
    <!-- 面包屑区域 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图区域 -->
    <el-card class="box-card">
      <!-- 隔栅视图 , 间隔20px -->
      <el-row :gutter="20">
        <el-col :span="10">
          <el-input clearable placeholder="请输入内容" class="input-with-select" v-model="requestInfo.query" @clear="getUserInfo">
            <el-button slot="append" icon="el-icon-search" @click="getUserInfo"></el-button>
          </el-input>
        </el-col>
        <el-col :span="4"><el-button type="primary" @click="dialogVisible = true">添加用户</el-button></el-col>
      </el-row>
      <!-- 表格区域 -->
      <!-- users为要渲染的数组 -->
      <el-table :data="users" style="width: 100%" stripe border>
        <!-- prop指定要渲染的数据   label 为当前列标题 -->
        <el-table-column type="index"> </el-table-column>
        <el-table-column prop="username" label="姓名"> </el-table-column>
        <el-table-column prop="email" label="邮箱"> </el-table-column>
        <el-table-column prop="mobile" label="电话"> </el-table-column>
        <el-table-column prop="role_name" label="角色"> </el-table-column>

        <el-table-column label="状态">
          <!-- 获取当前行数据 -->
          <template slot-scope="scope">
            <!-- v-model使用当前行数据 -->
            <el-switch v-model="scope.row.mg_state" @change="changeUserStatus(scope.row)"> </el-switch>
          </template>
        </el-table-column>

        <el-table-column label="操作" width="180">
          <!-- template 插入自定义内容 -->
          <template slot-scope="scope">
            <!-- {{ scope.row.id }} -->
            <el-button size="mini" type="primary" icon="el-icon-edit" @click="updateUserFn(scope.row.id)"></el-button>

            <el-button @click="deleteUser(scope.row.id)" size="mini" type="danger" icon="el-icon-delete"></el-button>
            <!-- 文字提示消息 -->
            <el-tooltip :enterable="false" effect="dark" content="分配角色" placement="top">
              <el-button @click="setUserRoleFn(scope.row)" size="mini" type="warning" icon="el-icon-setting"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区域 -->
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="requestInfo.pagenum" :page-sizes="[1, 2, 3, 4]" :page-size="requestInfo.pagesize" layout="total, sizes, prev, pager, next, jumper" :total="total"> </el-pagination>
    </el-card>

    <!-- 添加用户对话框区域 -->
    <el-dialog @close="formReset" title="添加用户信息" :visible.sync="dialogVisible" width="50%">
      <!-- 对话框内容区域 -->
      <el-form :model="addFormInfo" :rules="addrules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addFormInfo.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addFormInfo.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addFormInfo.email"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="addFormInfo.mobile"></el-input>
        </el-form-item>
      </el-form>
      <!-- 对话框底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUserInfo">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改用户信息区域对话框 -->
    <el-dialog @close="resetUpdateInfo" title="修改用户信息" :visible.sync="editDialogVisible" width="50%">
      <!-- 弹框内容 -->
      <el-form :model="updateUserInfo" :rules="updateUserInfoRules" ref="updateruleForm" label-width="100px" class="demo-ruleForm">
        <el-form-item label="用户名">
          <el-input v-model="updateUserInfo.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="updateUserInfo.email"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="updateUserInfo.mobile"></el-input>
        </el-form-item>
      </el-form>
      <!-- 弹框底部 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="updateUserInfoFn">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 分配用户角色弹框 -->
    <el-dialog @close="clearUserRoleid" title="分配角色" :visible.sync="setUserRoledialogVisible" width="50%">
      <el-row>
        <el-col class="setmargin">当前用户 : {{ currentUserInfo.username }}</el-col>
      </el-row>
      <el-row>
        <el-col class="setmargin">当前的角色 : {{ currentUserInfo.role_name }}</el-col>
      </el-row>
      <el-row :gutter="10">
        <el-col class="setmargin"
          >分配新角色 : <el-select v-model="roleId" placeholder="请选择"> <el-option v-for="item in roleList" :key="item.id" :label="item.roleName" :value="item.id"> </el-option> </el-select
        ></el-col>
      </el-row>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setUserRoledialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="setUserRolebyIdFn">确 定</el-button>
      </span>
    </el-dialog>

  </div>
</template>

<script>
import { setUsersRole, getAllRolesList, getUserInfo, changeUserStatus, addUserList, getUserInfobyId, UpdateUserInfo, deleteUserInfo } from '@/api/index.js'
export default {
  created() {
    // 获取用户数据
    this.getUserInfo()
    //获取当前角色列表
    getAllRolesList().then((res) => {
      if (res.data.meta.status != 200) {
        this.$message.error('获取角色列表失败')
      } else {
        this.roleList = res.data.data
      }
    })
  },
  data() {
    var checkEmail = (rule, value, callback) => {
      const reg = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-])+/
      //返回callback()  代表校验成功
      if (reg.test(value)) return callback()
      //校验失败
      callback(new Error('邮箱输入错误'))
    }
    var checkPhone = (rule, value, callback) => {
      const regs = /^((13[0-9])|(17[0-1,6-8])|(15[^4,\\D])|(18[0-9]))\d{8}$/
      if (regs.test(value)) return callback()
      callback(new Error('手机号输入错误'))
    }
    return {
      //选中角色id
      roleId: '',
      // 角色列表
      roleList: [],
      //当前用户信息
      currentUserInfo: {},
      //分配用户角色弹框
      setUserRoledialogVisible: false,
      // 添加用户信息
      addFormInfo: {
        username: '',
        password: '',
        email: '',
        mobile: '',
      },
      addrules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' },
        ],
        password: [{ required: true, message: '请输入密码', trigger: 'blur' }],

        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          //使用自定义校验规则
          { validator: checkEmail, trigger: 'blur' },
        ],

        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: checkPhone, trigger: 'blur' },
        ],
      },
      //添加用户对话框
      dialogVisible: false,
      //是否显示修改用户对话框
      editDialogVisible: false,
      //查询用户列表参数
      requestInfo: {
        query: '',
        pagenum: 1,
        pagesize: 2,
      },
      //修改用户数据
      updateUserInfo: {
        id: '',
        username: '',
        mobile: '',
        email: '',
      },
      // 修改用户数据校验规则
      updateUserInfoRules: {
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          //使用自定义校验规则
          { validator: checkEmail, trigger: 'blur' },
        ],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: checkPhone, trigger: 'blur' },
        ],
      },
      pagenum: 0,
      total: 0,
      users: [],
    }
  },
  methods: {
    //清空用户信息，角色id
    clearUserRoleid(){
      this.currentUserInfo={}
      this.roleId=''
    },
    //分配用户角色请求发送
    async setUserRolebyIdFn() {
      let { data: res } = await setUsersRole(this.currentUserInfo.id, this.roleId)
      if (res.meta.status != 200) {
        this.$message.error('分配角色失败')
      }
      //提示信息
      this.$message.success('分配角色成功')
      //数据回显
      this.getUserInfo()
      //关闭弹窗
      this.setUserRoledialogVisible = false
    },
    //分配用户角色弹框
    setUserRoleFn(roleInfo) {
      //存储当前用户信息
      this.currentUserInfo = roleInfo
      this.setUserRoledialogVisible = true
    },
    //删除用户数据对话框
    deleteUser(id) {
      this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(async () => {
          //发送请求，接受返回值
          let { data: res } = await deleteUserInfo(id)
          //判断请求成功还是失败
          //请求成功后，提示信息，数据回显
          if (res.meta.status == 200) {
            this.$message({
              type: 'success',
              message: '删除成功!',
            })
            this.getUserInfo()
          } else {
            //请求失败后，提示信息
            this.$message.error('删除失败')
          }
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除',
          })
        })
    },
    //更新用户数据
    updateUserInfoFn() {
      // valid 为当前表单校验是否通过,通过返回为 true，不通过返回为false
      this.$refs.updateruleForm.validate(async (valid) => {
        if (valid) {
          let { data: res } = await UpdateUserInfo({ email: this.updateUserInfo.email, mobile: this.updateUserInfo.mobile }, this.updateUserInfo.id)
          if (res.meta.status == 200) {
            //数据回显
            this.getUserInfo()
            //关闭弹框
            this.editDialogVisible = false
            //提示用户
            this.$message.success('更新用户数据成功')
          } else {
            this.$message.error('更新用户数据失败')
            editDialogVisible = false
          }
        } else {
          return
        }
      })
      // editDialogVisible = false
    },
    // 重置更新表单数据
    resetUpdateInfo() {
      this.$refs.updateruleForm.resetFields()
    },
    //根据用户id查询用户信息
    async updateUserFn(id) {
      // 根据id 查询用户信息
      let { data: res } = await getUserInfobyId(id)

      if (res.meta.status == 200) {
        // data中存储用户信息
        this.updateUserInfo = res.data
      } else {
        this.$message.error('获取用户信息失败，请重新尝试')
      }
      //显示弹框
      this.editDialogVisible = true
    },
    //添加用户
    addUserInfo() {
      this.$refs.ruleForm.validate(async (valid) => {
        //校验通过后 valid为true
        if (valid) {
          this.dialogVisible = false
          //发送请求添加用户信息
          let { data: res } = await addUserList(this.addFormInfo)
          if (res.meta.status == 201) {
            //添加成功后用户数据回显
            this.getUserInfo()
            this.$message.success('添加用户成功')
          } else {
            this.$message.error('添加用户失败')
          }
        } else {
          //valid为false，校验未通过执行
          return
        }
      })
    },
    formReset() {
      this.$refs.ruleForm.resetFields()
    },
    //修改用户状态事件
    async changeUserStatus(userInfo) {
      console.log(userInfo)
      let { data: res } = await changeUserStatus(userInfo.id, userInfo.mg_state)
      if (res.meta.status == 200) {
        this.$message.success('更新用户状态成功')
      } else {
        this.$$message.error('更新用户状态失败')
      }
    },
    //当前页展示数据条数改变
    handleSizeChange(pagesize) {
      //修改当前页数据条数
      this.requestInfo.pagesize = pagesize
      //发送请求获取数据
      this.getUserInfo()
    },
    //当前页改变事件
    handleCurrentChange(currentpage) {
      // 修改当前页
      this.requestInfo.pagenum = currentpage
      //发送请求获取数据
      this.getUserInfo()
    },
    // 获取用户数据
    async getUserInfo() {
      let { data: res } = await getUserInfo(this.requestInfo)
      console.log(res)
      if (res.meta.status != 200) return this.$message.error('获取数据失败')
      this.pagenum = res.data.pagenum
      this.total = res.data.total
      this.users = res.data.users
    },
  },
}
</script>

<style lang="less" scoped>
.setmargin {
  margin: 7px;
}
.el-breadcrumb {
  margin-bottom: 12px;
  font-size: 12px;
}
.el-table {
  margin-top: 12px;
}
</style>
